#include "timer.h"
Timer *Timer_new(){
    Timer * newTimer = (Timer*) malloc (sizeof(Timer));
    if (!newTimer) return NULL;
    newTimer->time = 0;
    newTimer->offset = 0;
    newTimer->status = 1;
    newTimer->oldtime = clock();
    return newTimer;
}

unsigned long Timer_get(Timer *timer){
    if(timer->status==1)
        timer->time=clock()-timer->oldtime+timer->offset;
    else if(timer->status==0)
        timer->oldtime=clock()-timer->time;
    return timer->time;
}

void Timer_pause(Timer *timer){
    if(timer->status==1)
        timer->status=0;
}

void Timer_resume(Timer *timer){
    if(timer->status==0)
        timer->status=1;
}

void Timer_stop(Timer *timer){
    timer->status=2;
}

void Timer_start(Timer *timer){
    if(timer->status==2){
        timer->oldtime=clock();
        timer->status=1;
    }
}

void Timer_reset(Timer *timer,long count){
    if(count!=NULL){
        timer->offset=count;
        Timer_stop(timer);
    }else{
        timer->time=0;
        Timer_stop(timer);
    }
    
}

void Timer_term(Timer *timer){
    free(timer);
}

char *Timer_status(Timer *timer){
    char * msg;
    if(timer->status==0){
        msg=(char*)malloc(6);
        strcpy(msg,"pause");
    }else if(timer->status==1){
        msg=(char*)malloc(8);
        strcpy(msg,"running");
    }else{
        msg=(char*)malloc(5);
        strcpy(msg,"stop");
    }
    return msg;
}
